<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item>
      <div class="XiTongname">系统名称</div>
      <el-select v-model="loginForm.strDengLuXiTong">
        <el-option :label="item" :value="item" v-for="(item, i) in systemname" :key="i" />
      </el-select>
    </el-form-item>

    <el-form-item prop="strUserId">
      <div class="XiTongname">用户代码</div>
      <div class="usercodebox">
        <el-input
          v-model="loginForm.strUserId"
          style="width: 35%"
          @blur="handleBlur('strPassWord')"
          @keyup.enter="handleBlur('strPassWord')"
        />
        <el-select style="width: 23%; margin-left: 10px" disabled v-model="loginForm.strYuanQu">
          <el-option v-for="(item, i) in yuanqu" :key="i" :label="item" :value="item" />
        </el-select>
      </div>
    </el-form-item>

    <el-form-item>
      <div class="XiTongname">用户名称</div>
      <el-input v-model="loginForm.strUserName" disabled />
    </el-form-item>

    <el-form-item prop="strPassWord">
      <div class="XiTongname">登陆密码</div>
      <el-input ref="passwordInput" @keyup.enter="login(loginFormRef)" v-model="loginForm.strPassWord" show-password />
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { ElNotification } from "element-plus";
// import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { SelUserDateport, Loginport } from "@/api/modules/user";
// import md5 from "md5";
import { loginStore } from "@/stores/login/index";

const initloginStore = loginStore();

const passwordInput = ref();
const systemname = ref<any>([]);
const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  strUserId: [{ required: true, message: "请输入用户代码", trigger: "blur" }],
  strPassWord: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const yuanqu = ref([]);
const loading = ref(false);
const loginForm = reactive<any>({
  strDengLuXiTong: "",
  strUserId: "",
  strUserName: "",
  strYuanQu: "",
  strPassWord: ""
});

const handleBlur = (nextField: any) => {
  if (nextField === "strPassWord") {
    passwordInput.value.focus();
  }
  const data = {
    strstrUserId: loginForm.strUserId
  };
  SelUserDateport(data).then((res: any) => {
    console.log(res);
    if (res.Success == 0) {
      loginForm.strUserName = res.Data.UserName;
      yuanqu.value = res.Data.YuanQu;
      loginForm.strUserId = loginForm.strUserId;
      loginForm.strYuanQu = res.Data.YuanQu[0] ? res.Data.YuanQu[0] : "";
    }
  });
};
// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      // const { data } = await loginApi({ ...loginForm, password: md5(loginForm.password) });
      Loginport(loginForm).then((res: any) => {
        if (res.Success == 0) {
          console.log(res, "alluser.valuealluser.value");
          userStore.setToken(res.Data.userInfo.token);
          localStorage.setItem("token", res.Data.userInfo.token);
          // 2.添加动态路由
          initDynamicRouter();
        }
      });
      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);
      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录 Geeker-Admin",
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};

onMounted(() => {
  loginForm.strDengLuXiTong = initloginStore.XiTongname ? initloginStore.XiTongname[0] : "";
  nextTick(() => {
    systemname.value = initloginStore.XiTongname;
    console.log(systemname.value, "itemitemitemitemitemitem");
  });
  // 监听 enter 事件（调用登录）
  // document.onkeydown = (e: KeyboardEvent) => {
  //   e = (window.event as KeyboardEvent) || e;
  //   if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
  //     if (loading.value) return;
  //     login(loginFormRef.value);
  //   }
  // };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
